package com.why.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.why.pojo.News;
import com.why.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class NewsController {

    @Autowired
    NewsService newsService;

    //查询最新5条新闻
    @GetMapping(value = "getnewslist",produces = "application/json;charset=utf-8")
    public String getNewsList(){
        List<News> newsList = newsService.newsList();
        return JSON.toJSONString(newsList);
    }

    //查询分页新闻
    @RequestMapping(value = "/newsPage",produces = "application/json;charset=utf-8")
    public PageInfo<News> newsPage(Integer pageNum, Integer pageSize){
        return newsService.selectPage(pageNum, pageSize);
    }

    //根据id查询新闻
    @RequestMapping(value = "/selectNewsByID",produces = "application/json;charset=utf-8")
    public News selectNewsByID(Integer id){
        return newsService.selectByPrimaryKey(id);
    }

    //根据id删除新闻
    @RequestMapping("/deleteNews")
    public String deleteNews(Integer id){
        if (newsService.deleteByPrimaryKey(id)){
            return "success";
        }
        return "failed";
    }
    //新增新闻
    @RequestMapping("/addNews")
    public String addNews(News news){
        if (newsService.insertSelective(news)){
            return "success";
        }
        return "failed";
    }
    //修改新闻
    @RequestMapping("/updateNews")
    public String updateNews(News news){
        if (newsService.updateByPrimaryKeySelective(news)){
            return "success";
        }
        return "failed";
    }

    //判断新闻标题是否唯一
    @RequestMapping("/isTitle")
    public String isTitle(String title){
        News news = newsService.selectNewsByTitle(title);
        if (null==news){
            return "success";
        }
        return "failed";
    }
}
